package com.labor_management_system.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.labor_management_system.Entity.Attendance;
import com.labor_management_system.Entity.Team;
import com.labor_management_system.Service.AttendanceService;
import com.labor_management_system.Service.EmployeeService;
import com.labor_management_system.Service.TeamService;
import com.labor_management_system.Utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

import static com.labor_management_system.Utils.TimeUtil.getMidnightTimestampOfToday;
import static com.labor_management_system.Utils.TimeUtil.getMidnightTimestampOfTomorrow;
@RestController
@CrossOrigin
public class NumberOfWorkersController {
    //上工人数管理
    @Autowired
    AttendanceService attendanceService;
    @Autowired
    TeamService teamService;
    @Autowired
    EmployeeService employeeService;
//
//    List<TeamAttendance> teamAttendanceList;
//    Map<String, List<String>> TeamVEmployee;
//    List<TeamAttendanceDetails> teamAttendanceDetailsList;

    /**
     * 根据具体时间日期(某一日的数据)
     * time 格式2024-01-02
     * @param
     * @return
     */
    @GetMapping("/numberOfWorkers/day")
    public R simulateWorking(Page page, String time) throws ParseException {

        //以团队数据为分页基础，先查出团队分页
        IPage<Team> teams = teamService.page(page);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = simpleDateFormat.parse(time);

        for(Team item : teams.getRecords()){
            QueryWrapper<Attendance> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("employee_id ,count(*)" )
                    .between("start_work",getMidnightTimestampOfToday(date.getTime()),getMidnightTimestampOfTomorrow(date.getTime()))
                    .inSql("employee_id" ,"select employee_id from employee where team_id="+item.getTeamId())
                    .groupBy("employee_id");
            Integer count = attendanceService.getBaseMapper().selectMaps(queryWrapper).size();
            item.setVolumeUpSize(count);
        }
        return R.ok().data("info",teams);
    }

    /**
     * 根据传入的当前月份，返回该月份内天数有异常的信息
     * attendanceDate 格式2024-01
     * @return
     */
    @GetMapping("/numberOfWorkers/month")
    public R month(String attendanceDate) {
        String[] time = attendanceDate.split("-");
        LocalDate date = LocalDate.of(Integer.parseInt(time[0]), Integer.parseInt(time[1]), 1);
        LocalDate now = LocalDate.now();
        //计算当前月份有多少天
        int days = date.lengthOfMonth();
        //查询所有团队
        List<Team> teams = teamService.list();
        //存放有考勤异常的日期级数据
        Map<String,Object> dateMap = new HashMap<>();
        //从传入日期第一天开始整合数据
        for(int i = 1; i<=days;i++){
            List<Map<String,Object>> infos = new ArrayList<>();
            Map<String,Object> map = new HashMap<>();
            if(!date.isBefore(now)) break;
            if(i!=1)
                date = date.plusDays(1);
            LocalDateTime startOfDay = date.atStartOfDay();
            long millis = startOfDay.toInstant(ZoneOffset.of("+8")).toEpochMilli();
            for(Team item : teams){
                QueryWrapper<Attendance> queryWrapper = new QueryWrapper<>();

                queryWrapper.select("employee_id ,count(*)" )
                        .between("start_work",getMidnightTimestampOfToday(millis),getMidnightTimestampOfTomorrow(millis))
                        .inSql("employee_id" ,"select employee_id from employee where team_id="+item.getTeamId())
                        .groupBy("employee_id");
                //获取团队当天实际到岗人数
                Integer count = attendanceService.getBaseMapper().selectMaps(queryWrapper).size();
                if(item.getTeamSize()-count!=0){ //考勤人数和实际人数不一致进入
                    map.put("tname",item.getTeamName());
                    map.put("num",item.getTeamSize()-count);
                    infos.add(map);
                }
            }
            if(map.size()!=0){
                if(days<10){
                    dateMap.put(attendanceDate+"-0"+i,infos);
                }else{
                    dateMap.put(attendanceDate+"-"+i,infos);
                }
            }
        }
        return R.ok().data("info",dateMap);
    }

}
